using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using AiyoriAoshi.MangaService;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Xml;
using System.IO;
using System.Windows.Resources;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Net.NetworkInformation;
using DBDataContext.Model;

namespace AiyoriAoshi
{
    public partial class IntroPage : PhoneApplicationPage
    {
        private IsolatedStorageSettings issSetting = IsolatedStorageSettings.ApplicationSettings;

        // Constructor
        public IntroPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(IntroPage_Loaded);

        }

        void IntroPage_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void btnRead_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ChaptersPage.xaml", UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (issSetting.Contains("ShowOnStartup") == false)
            {
                issSetting.Add("ShowOnStartup", true);
                issSetting.Save();
                this.ckbShowStartUp.IsChecked = true;
            }
            else
            {
                if ((bool)issSetting["ShowOnStartup"] == false)
                {
                    //NavigationService.Navigate(new Uri("/ChaptersPage.xaml", UriKind.Relative));
                }
                else
                {
                    this.ckbShowStartUp.IsChecked = true;
                }
            }

            // if it's first time launching this app, ISS doesn't have IsLoadedMangaDetail key and doesn't have ShowOnStartup key
            if (issSetting.Contains("IsLoadedMangaDetail"))
            {
                if ((bool)issSetting["IsLoadedMangaDetail"] == false)
                {
                    //LoadMangaStoryDetail();
                }
                else
                {
                    ShowMangaDetail();
                }
            }
            else
            {
                issSetting.Add("IsLoadedMangaDetail", false);
                issSetting.Save();
                //LoadMangaStoryDetail();
            }
            base.OnNavigatedTo(e);
        }

        private void LoadMangaStoryDetail()
        {
            this.TitlePanel.Visibility = Visibility.Collapsed;
            //this.LoadingPanel.Visibility = Visibility.Visible;
            //this.barLoading.IsIndeterminate = true;

            //this.tbkLoadingStatus.Text += "\nLoading manga detail...";

            var ni = NetworkInterface.NetworkInterfaceType;

            //if (NetworkInterface.GetIsNetworkAvailable() == false)
            if (ni == NetworkInterfaceType.None)
            {
                //MessageBox.Show("Bạn không có kết nối internet. Vui lòng thử lại.");
                //this.tbkLoadingStatus.Text = "Can't load manga detail. Please check your phone network connection.";
                //this.tbkLoadingStatus.Text = "This application needs phone network connection to load manga detail. Please try again.";
                //this.imgNoConnection.Visibility = Visibility.Visible;
                //this.barLoading.IsIndeterminate = false;
                return;
            }

            MangaServiceClient mangaService = new MangaServiceClient();
            mangaService.GetMangaStoryDetailAsync(App.KEYSITE, App.LINKMANGA);
            mangaService.GetMangaStoryDetailCompleted += (sender, args) =>
            {
                try
                {
                    // Insert manga detail
                    int mangaIdAfterInsert = App.ViewModel.InsertMangaReturnMangaId(args.Result);

                    // save title
                    if (issSetting.Contains("MangaId"))
                    {
                        issSetting["MangaId"] = mangaIdAfterInsert;
                    }
                    else
                    {
                        issSetting.Add("MangaId", mangaIdAfterInsert);
                    }

                    // Insert chapters detail
                    App.ViewModel.InsertChaptersBaseOnMangaId(mangaIdAfterInsert, args.Result.Chapters.ToList<MangaChapter>());

                    // Finish saving, change state of loadedDetail
                    issSetting["IsLoadedMangaDetail"] = true;
                    issSetting.Save();

                    // Load Manga Image
                    //this.tbkLoadingStatus.Text += "\nLoading manga image...";
                    WebClient webDownloadMangaImage = new WebClient();
                    webDownloadMangaImage.OpenReadAsync(new Uri(args.Result.ImageLink, UriKind.Absolute));
                    webDownloadMangaImage.OpenReadCompleted += (s, e) =>
                        {
                            try
                            {
                                
                                using (IsolatedStorageFile isoForMangaImage = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    string tempJPEG = "MangaImage.jpg";

                                    if (isoForMangaImage.FileExists(tempJPEG))
                                    {
                                        isoForMangaImage.DeleteFile(tempJPEG);
                                    }

                                    IsolatedStorageFileStream fileStream = isoForMangaImage.CreateFile(tempJPEG);

                                    Uri uri = new Uri(tempJPEG, UriKind.Relative);

                                    BitmapImage bitmap = new BitmapImage();
                                    bitmap.SetSource(e.Result);
                                    WriteableBitmap wb = new WriteableBitmap(bitmap);

                                    // Encode WriteableBitmap object to a JPEG stream.
                                    System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);

                                    //wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
                                    fileStream.Close();

                                    Debug.WriteLine("Download manga image successfully!!!");
                                    ShowMangaDetail();
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Error downloading/saving image. Message: " + ex.Message);
                                //this.barLoading.IsIndeterminate = false;
                            }
                        };
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error saving manga detail. Message: " + ex.Message);
                    //this.barLoading.IsIndeterminate = false;
                }
            };
        }

        private void ShowMangaDetail()
        {
            try
            {
                this.TitlePanel.Visibility = Visibility.Visible;
                //this.LoadingPanel.Visibility = Visibility.Collapsed;
                //this.barLoading.IsIndeterminate = false;

                Manga manga = App.ViewModel.GetMangaByMangaId((int)issSetting["MangaId"]);

                this.tbkName.Text = manga.Title;
                this.tbkAuthor.Text = "Author: " + manga.Author;
                this.tbkSummary.Text = manga.Summary;

                //using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                //{
                //    //string path = String.Format("Shared/Download/{0}/{1}", manga.FolderName, manga.ImageName);
                //    using (IsolatedStorageFileStream isfs = isf.OpenFile("MangaImage.jpg", FileMode.Open, FileAccess.Read))
                //    {
                //        byte[] data;

                //        // Allocate an array large enough for the entire file
                //        data = new byte[isfs.Length];

                //        // Read the entire file and then close it
                //        isfs.Read(data, 0, data.Length);
                //        isfs.Dispose();
                //        isfs.Close();

                //        // Create memory stream and bitmap
                //        MemoryStream ms = new MemoryStream(data);

                //        BitmapImage bi = new BitmapImage();

                //        // Set bitmap source to memory stream
                //        bi.SetSource(ms);

                //        // Assign the bitmap image to the image’s source
                //        this.imgManga.Source = bi;
                //    }
                //    isf.Dispose();
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error showing manga detail. Message: " + ex.Message);
            }
        }

        private void ckbShowStartUp_Checked(object sender, RoutedEventArgs e)
        {
            if (issSetting.Contains("ShowOnStartup") == false)
            {
                issSetting.Add("ShowOnStartup", true);
            }
            else
            {
                issSetting["ShowOnStartup"] = true;
            }
            issSetting.Save();
        }

        private void ckbShowStartUp_Unchecked(object sender, RoutedEventArgs e)
        {
            if (issSetting.Contains("ShowOnStartup") == false)
            {
                issSetting.Add("ShowOnStartup", false);
            }
            else
            {
                issSetting["ShowOnStartup"] = false;
            }
            issSetting.Save();
        }
    }
}